import { ITreeItem } from "@/types/global";

/**
 * @desc 获取token
 */
export const getToken = (): string | null => {
  return window.localStorage.getItem("token");
};
/**
 * @desc 获取localStorage
 */
export const getLocalStorage = (key: string): any => {
  return JSON.parse(window.localStorage.getItem(key) || "{}");
};
/**
 * @desc 设置localStorage
 */
export const setLocalStorage = (key: string, value: any): void => {
  if (value) {
    window.localStorage.setItem(key, value);
  } else {
    window.localStorage.removeItem(key);
  }
};

/**
 * @description 验证手机号
 * @param phone 手机号
 * @returns 是否校验成功
 */
export function validatePhoneNumber(phone: string) {
  const regex = /^(1[3-9]\d{9})$|^((0\d{2,3})-?\d{7,8})$/;
  return regex.test(phone);
}

/**
 * @description: 将菜单列表转换为树形结构
 * @param menuList 菜单列表
 * @param treeMenuList 树形结构菜单列表
 */
export const menusToTree = (
  menuList: any[],
  treeMenuList: any[],
  permissions?: any[]
) => {
  for (let i = 0; i < menuList.length; i++) {
    const menuItem: any = menuList[i];
    // @ts-ignore
    const treeItem: ITreeItem = {};
    treeItem.id = menuItem.id;
    treeItem.label = menuItem.name;
    treeItem.children = [];
    treeItem.hasPerms = menuItem.hasPerms;
    if (permissions) {
      if (treeItem.hasPerms) {
        treeItem.perms = [];
        permissions.map((permission: any) => {
          if (permission.menuId === treeItem.id) {
            treeItem.perms!.push(permission);
          }
        });
      }
    }
    if (menuItem.children && menuItem.children.length > 0) {
      menusToTree(menuItem.children, treeItem.children, permissions);
    }
    treeMenuList.push(treeItem);
  }
};
